import React from "react";
import { Upload } from "antd";
import { RcFile } from "antd/lib/upload";
import { notification } from "@/components/wocloud-antd";

export interface IUploadProps {
  isGt?: number;
  fileExtLimits?: string[];
  [propsName: string]: any;
}

const defaultBeforeUpload = (
  file: RcFile,
  isGt: number | undefined,
  fileExtLimits: string[] | undefined
) => {
  // 文件大小限制
  const nisGt = file.size / 1024 / 1024 > (isGt || 20);
  if (nisGt) {
    notification.warn("上传文件不能大于20MB");
    return Promise.reject(file);
  }
  // 文件扩展名限制
  const fileExtMatch: any = file.name.match(/\.([^\.]+)$/);
  const nfileExtLimits: any = [...(fileExtLimits || [])];
  if (
    !fileExtMatch ||
    !nfileExtLimits.includes(fileExtMatch[1].toLowerCase())
  ) {
    notification.warn(`上传文件格式仅支持：${nfileExtLimits.join("、")}`);
    return Promise.reject(file);
  }
  return Promise.resolve(file);
};

const CustomizedUpload: React.FC<any> = (props: IUploadProps) => {
  const defaultProps: any = {
    ...props,
    beforeUpload: (file: RcFile) => {
      defaultBeforeUpload(file, props.isGt, props.fileExtLimits);
      props.beforeUpload(file);
    },
  };
  return <Upload {...defaultProps} />;
};

export default CustomizedUpload;
